<?php

namespace App\Services\Assess;

use App\Helpers\JwtUtils;
use App\Models\Account\UserAccountModel;
use App\Models\Assess\GiftPlatformSkuModel;
use App\Models\Assess\GiftModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use Illuminate\Support\Facades\DB;

/**
 * 礼品设置Service层
 */
class GiftSetService extends BaseService
{
    //是否展示收货地址
    public $addressDisplay = [
        ['label' => '是', 'val' => 1],
        ['label' => '否', 'val' => 2]
    ];
    //对应放卡片的产品市场
    public $country = ['No' => '暂无指定', 'US' => 'United States (US)'];
    //对应放卡片的产品Asin
    public $platformSkuType = [
        ['label' => '普通添加', 'val' => 1],
        ['label' => '批量添加', 'val' => 2]
    ];
    //状态
    public $status = [
        ['label' => '开', 'val' => 1],
        ['label' => '关', 'val' => 2]
    ];
    //星级
    public $starRatingRetention = [
        ['label' => '1星', 'val' => 1],
        ['label' => '2星', 'val' => 2],
        ['label' => '3星', 'val' => 3],
        ['label' => '4星', 'val' => 4],
        ['label' => '5星', 'val' => 5],
        ['label' => '不引导留评', 'val' => 0],
    ];
    //礼品类型
    public $giftType = [
        1=>'返现',
        2=>'配件',
        3=>'Amazon礼品卡'
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new GiftModel();
    }


    /**
     * @Notes:获取礼品配置信息
     * @Interface getGiftConfig
     * @author: wuyu
     * @Time: 2023/4/21   18:08
     */
    public function getGiftConfig()
    {

        $GiftPlatformSkuModel = new GiftPlatformSkuModel();
        $platformSkuList = $GiftPlatformSkuModel->groupBy('platform_sku')->get('platform_sku')->toArray();
        $platformSkuListCol = array_column($platformSkuList, 'platform_sku');
        $config = [];
        $config['address_display'] = $this->addressDisplay;
        $config['country'] = (new OrderAndCustomersOrderService())->country;
        $config['platform_sku_type'] = $this->platformSkuType;
        $config['status'] = $this->status;
        $config['star_rating_retention'] = $this->starRatingRetention;
        $config['gift_type_list'] = $this->giftType;
        $config['platform_sku_select'] = $platformSkuListCol;
        $config['gift_image'] = IMG_URL . '\uploads\images\gift\gift_1.png';

        return message("获取成功", true,$config);

    }

    /**
     * @Notes:获取订单对应的sku
     * @Interface getOrderSku
     * @author: wuyu
     * @Time: 2023/7/6   22:25
     */
    public function getOrderSku()
    {
        $param = request()->all();
        $sku = $param['sku'] ?? '';
        if (empty($sku)) return message("获取失败", false, []);

        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $platformSkuList = $OrderAndCustomersOrderDetailModel->where('platform_sku','like',"%{$sku}%")->limit(500)->groupBy(['platform_sku'])->get(['platform_sku'])->toArray();

        $platformSkuList = array_column($platformSkuList,'platform_sku');

        return message("获取成功", true,$platformSkuList);

    }


    public function getList()
    {
        $param = request()->all();

        // 查询条件
        $map[] = ["m.mark", '=', 1];
        $name = getter($param, "name");
        $platformSku = getter($param, "platform_sku");
        $country = getter($param, "country");
        $giftType = getter($param, "gift_type");
        $sort = $param['sort'] ?? 'm.sort';
        $order = $param['order'] ?? 'DESC';
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);

        $platformSkuStr = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $platformSku);
        if (!empty($platformSkuStr)) $platformSkuArr = array_unique(explode(';', $platformSkuStr));
        if ($name) $map[] = ["m.name", 'like', "%{$name}%"];
        if ($country) $map[] = ["m.country", '=', $country];
        if ($giftType) $map[] = ["m.gift_type", '=', $giftType];

        $GiftAsinModel = new GiftPlatformSkuModel();

        //权限过滤 组员可以看一个组的信息
//        $createUserAuth = CommonService::userAuth();
        $skuAuth = CommonService::skuAuth();

        $mainTable = $this->model->getTable();
        $sonTable = $GiftAsinModel->getTable();
        $offset = (PAGE - 1) * PERPAGE;
        $model = $this->model::from("$mainTable as m")
            ->select('m.*')
            ->join("$sonTable as s", 's.gift_id', '=', 'm.id')
            ->distinct(true)
            ->where($map);
        $model2 = $this->model::from("$mainTable as m")
            ->select('m.id')
            ->join("$sonTable as s", 's.gift_id', '=', 'm.id')
            ->distinct('m.id')
            ->where($map);
        if (!empty($platformSkuArr)){
            $model->whereIn('s.platform_sku', $platformSkuArr);
            $model2->whereIn('s.platform_sku', $platformSkuArr);
        }

        if (!empty($skuAuth) && empty($platformSkuArr)){
            $model->whereIn('s.platform_sku', $skuAuth);
            $model2->whereIn('s.platform_sku', $skuAuth);
        }

        $result = $model
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();

        $count = $model2->count();

        //获取子信息
        $mainIds = [];
        if (!empty($result)) $mainIds = array_column($result, 'id', 'id');
        $sonList = $GiftAsinModel->whereIn('gift_id', $mainIds)->get(['gift_id', 'platform_sku'])->toArray();
        $sonGroupList = [];
        foreach ($sonList as $kk => $vv) {
            $sonGroupList[$vv['gift_id']][] = $vv;
        }
        $list = [];
        $OrderAndCustomersOrderService = new OrderAndCustomersOrderService();
        if ($result) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val['id']);
                if (!$info) {
                    continue;
                }
                $platformSku = [];
                $AsinData = $sonGroupList[$val['id']] ?? [];
                foreach ($AsinData as $v2) {
                    $platformSku[] = $v2['platform_sku'];
                }
                $info['platform_sku'] = implode(';', $platformSku);
                $info['platform_sku_desc'] = implode(';', $platformSku);
                $info['platform_sku_select'] = $platformSku;
                $info['gift_type_text'] = $this->giftType[$val['gift_type']] ?? '';
                $info['country_name'] = $OrderAndCustomersOrderService->country[$info['country']] ?? $info['country'];
                if (!empty($info['image'])) $info['image'] = IMG_URL . $info['image'];
                $list[] = $info;
            }
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
    }

    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }

    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/11
     * @author 牧羊人
     */
    public function edit()
    {
        DB::connection($this->model->connection)->beginTransaction(); //开启事务
        try {
            $params = request()->all();
            $data = [
                'name' => $params['name'] ?? '',
                'country' => $params['country'] ?? '',
                'address_display' => $params['address_display'] ?? '',
                'platform_sku_type' => $params['platform_sku_type'] ?? 0,
                'desc' => $params['desc'] ?? '',
                'status' => $params['status'] ?? 0,
                'gift_type' => $params['gift_type'] ?? 0,
                'email' => $params['email'] ?? '',
                'gift_link' => $params['gift_link'] ?? '',
                'star_rating_retention' => $params['star_rating_retention'] ?? '',
                'image' => $params['image'] ?? '',
            ];

            // 图片处理
            $image = getter($data, "image");
            if (!empty($image)) {
                $data['image'] = str_replace(IMG_URL, "", $image);
            }

            // 开启事务
            $userId = JwtUtils::getUserId();
            $platformSkuSelect = $params['platform_sku_select'] ?? '';
            $platformSkuDesc = $params['platform_sku_desc'] ?? '';
            if (!empty($data['create_user_name'])) unset($data['create_user_name']);
            if (!empty($data['update_user_name'])) unset($data['update_user_name']);
            if (!empty($params['id'])) {
                $id = $params['id'];
                $data['id'] = $id;
                $data['update_time'] = time();
                $this->model->where('id', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            } else {
                $data['create_user'] = $data['update_user'] = $userId;
                $data['create_time'] = time();
                $id = $this->model->insertGetId($data);
            }
            if (!$id) {
                throw new \Exception('保存失败');
            }
            $GiftAsinModel = new GiftPlatformSkuModel();
            if ($data['platform_sku_type'] == 1) {
                $platformSkuArr = $platformSkuSelect;
            } else {
                $platformSkuStr = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $platformSkuDesc);
                $platformSkuArr = array_unique(explode(';', $platformSkuStr));
            }

            if (empty($platformSkuArr)) throw new \Exception('请填写Asin');

            $GiftAsinModel->where('gift_id', $id)->delete();

            foreach ($platformSkuArr as $val) {
                $platformSkuData = [
                    'gift_id' => $id,
                    'platform_sku' => $val
                ];
                $GiftAsinModel->insert($platformSkuData);
            }

            DB::connection($this->model->connection)->commit(); //事务提交

            return message("保存成功", true, []);

        } catch (\Exception $e) {
            DB::connection($this->model->connection)->rollBack(); //事务回滚
            return message("保存失败:" . $e->getMessage(), false, []);
        }

    }


}
